package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.jwt.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class AdUserServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult register(AdUserDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword()))return paramError;
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user != null)return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该用户名已注册");
        user = new AdUser();
        user.setName(dto.getName());
        Random random = new Random();
        int salt = random.nextInt(900000) + 100000;
        String md5Pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        user.setPassword(md5Pwd);
        user.setSalt(""+salt);
        user.setStatus(9);
        user.setCreatedTime(new Date());
        save(user);
        return success;
    }

    @Override
    public ResponseResult login(AdUserDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword()))return paramError;
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user == null)return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"账号错误");
        String password = dto.getPassword();//前端传过来的明文密码
        String salt = user.getSalt();//表中的盐值
        String md5Pwd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (user.getPassword().equals(md5Pwd)){
            String token = AppJwtUtil.getToken(user.getId().longValue());
            user.setSalt("");
            user.setPassword("");
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("token",token);
            resultMap.put("user",user);
            return success(resultMap);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
    }
}
